﻿Imports OMANE.Common
Imports OMANE.Common.UI
Imports System.Collections.ObjectModel
Imports PTIC_GestionBDD
Imports System.Xml.Serialization
Imports System.Xml.Linq
Imports Microsoft.Practices.Prism.Commands

''' <summary>
''' 
''' </summary>
''' <remarks></remarks>
Public Class ModuleIndicateurs
    Implements IModule


    Shared _AppInstance As Application
    Shared _BddManager As BddManager
    Friend Shared IsInConceptionMode As Boolean = True
    Friend Shared MuteAllQuery As Boolean = False

    Private dashboards As V2ViewModelTabGroup
    Private dashboardmodels As V2ViewModelTabGroup
    Private datamodels As V2ViewModelTabGroup
    Private dimensionBanque As V2ViewModelTabGroup
    Private dimensionDateEnCours As V2ViewModelTabGroup
    Private dimensionGeneration As V2ViewModelTabGroup
    Private dimensionTotal As V2ViewModelTabGroup

    Friend Shared currentDataConfig As VMDataSourceConfigure

    Private Banques As New Dictionary(Of String(), V2ViewModelTabGroup)
    Private DateEncours As New Dictionary(Of String(), V2ViewModelTabGroup)
    Private DimensionTotals As New Dictionary(Of String(), V2ViewModelTabGroup)
    Dim dimensionglobal As V2ViewModelTabGroup

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Public ReadOnly Property Dependencies As System.Collections.Generic.IEnumerable(Of Common.ModuleReference) Implements Common.IModule.Dependencies
        Get

        End Get
    End Property
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Load() Implements Common.IModule.Load

    End Sub
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Reset(ByVal Application As Common.Application) Implements Common.IModule.Reset

        ' Indicateus.Instance.GetRepartition("Loki")

        _AppInstance = Application

        Dim dicTemplate = New Windows.ResourceDictionary()
        dicTemplate.Source = New Uri("/OMANE.Modules.Indicateurs;component/RessourcesTemplate.xaml", System.UriKind.Relative)
        _AppInstance.GetService(Of IUIService)().AddResourceDictionary(dicTemplate)


        Dim dicZoneModel = New Windows.ResourceDictionary()
        dicZoneModel.Source = New Uri("/OMANE.Modules.Indicateurs;component/Ressources.xaml", System.UriKind.Relative)
        _AppInstance.GetService(Of IUIService)().AddResourceDictionary(dicZoneModel)

        Dim menuindicateurs = _AppInstance.GetService(Of IUIService)().V2ViewModelAccordeonMenu.Indicateurs
        Dim treeroot = menuindicateurs.Body.Root

        Dim inputgroupsection = New ObservableCollection(Of IViewModelTabSection)

        Dim SASConnection As New PTIC_GestionBDD.ConnectionSAS()
        Dim manager As BddManager = New BddManager(SASConnection)


        'inputgroupsection.Add(New VMDataImport(manager))
        'inputgroupsection.Add(New VMCorrespondance(manager))
        _BddManager = manager

        inputgroupsection.Add(New VMDataImport(True))
        inputgroupsection.Add(New VMCorrespondance(True))

        Dim input = New V2ViewModelTabGroup() With {.Title = "Données", .TabGroup = inputgroupsection}
        Dim import = New V2ViewModelTabGroup() With {.Title = "Import", .TabGroup = inputgroupsection, .TabSection = inputgroupsection(0)}
        Dim corresp = New V2ViewModelTabGroup() With {.Title = "Correspondance", .TabGroup = inputgroupsection, .TabSection = inputgroupsection(1)}
        input.Children.Add(import)
        input.Children.Add(corresp)
        ' treeroot.Children.Add(input)

        Dim builder = New V2ViewModelTabGroup() With {.Title = "Modélisation"}
        datamodels = New V2ViewModelTabGroup() With {
            .Title = "Modeles de données",
            .TabGroup = New ObservableCollection(Of IViewModelTabSection)}
        dashboardmodels = New V2ViewModelTabGroup() With { _
            .Title = "Modeles de Tableaux de Bord", _
            .TabGroup = New ObservableCollection(Of IViewModelTabSection)}


        Dim resources = New V2ViewModelTabGroup() With { _
           .Title = "Ressources", _
           .TabGroup = New ObservableCollection(Of IViewModelTabSection)}
        dashboardmodels.Children.Add(resources)

        dashboardmodels.ContextualCommands.Add( _
            New ViewModelCommand("Ajouter un tableau de bord", _
                    New DelegateCommand(Of Object)(AddressOf AddDashboardModelDefinitionExecute, _
                                        AddressOf AddDashboardModelDefinitionCanExecute)))
        dashboardmodels.ContextualCommands.Add( _
          New ViewModelCommand("Charger un tableau de bord", _
                  New DelegateCommand(Of Object)(AddressOf LoadDashboardModelDefinitionExecute, _
                                      AddressOf LoadDashboardModelDefinitionCanExecute)))

        datamodels.ContextualCommands.Add( _
           New ViewModelCommand("Ajouter un indicateur", _
                New DelegateCommand(Of Object)(AddressOf AddDataModelExecute)))
        datamodels.ContextualCommands.Add( _
           New ViewModelCommand("Charger un indicateur", _
                New DelegateCommand(Of Object)(AddressOf LoadDataModelExecute)))
        datamodels.ContextualCommands.Add( _
                  New ViewModelCommand("Configurer la source de données", _
                         New DelegateCommand(Of Object)(AddressOf ConfigureDataSourceExecute)))

        builder.Children.Add(datamodels)
        builder.Children.Add(dashboardmodels)
        treeroot.Children.Add(builder)

        dashboards = New V2ViewModelTabGroup() With {.Title = "Tableaux de Bord"}
        dashboards.ContextualCommands.Add( _
            New ViewModelCommand("Charger un ensemble de modele de tableau de bord", _
                  New DelegateCommand(Of Object)(AddressOf LoadDashboardModel)))
        dashboards = New V2ViewModelTabGroup() With {.Title = "Tableaux de Bord"}
        dashboards.ContextualCommands.Add( _
            New ViewModelCommand("Charger un modele de tableau de bord", _
                  New DelegateCommand(Of Object)(AddressOf LoadGroupDashboardModel)))

        'dashboards.ContextualCommands.Add( _
        '          New ViewModelCommand("Configurer la source de données", _
        '                New DelegateCommand(Of Object)(AddressOf ConfigureDataSourceExecute)))

        dimensionglobal = New V2ViewModelTabGroup() With {.Title = "Vue Global"}
        dimensionBanque = New V2ViewModelTabGroup() With {.Title = "Vue Selon La Banque"}
        'dimensionDateEnCours = New V2ViewModelTabGroup() With {.Title = "Vue Selon La Date d'encours)"}
        'dimensionGeneration = New V2ViewModelTabGroup() With {.Title = "Vue Selon La génération"}
        'dimensionTotal = New V2ViewModelTabGroup() With {.Title = "Vue Selon Toutes Les dimensions"}

        dashboards.Children.Add(dimensionglobal)
        dashboards.Children.Add(dimensionBanque)
        'dashboards.Children.Add(dimensionDateEnCours)
        'dashboards.Children.Add(dimensionGeneration)
        'dashboards.Children.Add(dimensionTotal)
        treeroot.Children.Add(dashboards)


        Dim banks = New String() {
          "ALPES", "ALSACE", "ATLANTIQUE", "FC", _
          "LORRAINE", "LL", "MC", "NORD", _
          "OC", "SUD", "SO", "VF", "RIVES"}

        Dim bankcodes = New String() {
            "BPA", "BPALS", "BPATL", "BPBFC", _
            "BPLC", "BPLL", "BPMC", "BPN", _
            "BPOC", "BPS", "BPSO", "BPVF", "RIVES"}

        Dim datecours = New String() {"JANVIER 2011", "JUIN 2010", "JANVIER 2010"}
        For i As Integer = 0 To banks.Length - 1
            Dim tg = New V2ViewModelTabGroup() With {.Title = banks(i)}
            dimensionBanque.Children.Add(tg)
            Banques.Add(New String() {banks(i), bankcodes(i)}, tg)
        Next
        'For Each elt In datecours
        '    Dim tg = New V2ViewModelTabGroup() With {.Title = elt}
        '    dimensionDateEnCours.Children.Add(tg)
        '    DateEncours.Add(New String() {elt, "date_encours=" & elt}, tg)
        'Next
        'For i As Integer = 0 To datecours.Length - 1
        '    Dim tg = New V2ViewModelTabGroup() With {.Title = datecours(i)}
        '    For j As Integer = 0 To banks.Length - 1
        '        Dim tg1 = New V2ViewModelTabGroup() With {.Title = banks(j)}
        '        tg.Children.Add(tg1)
        '        DimensionTotals.Add(New String() {"date_encours=" & datecours(i) & " and id_banque=" & banks(j)}, tg1)
        '    Next
        '    dimensionTotal.Children.Add(tg)
        'Next

        Dim topmenu = _AppInstance.GetService(Of IUIService)().ViewModelMainMenu.Edit

        topmenu.Children.Add(New ViewModelMainMenuItem() With { _
             .Title = "Mettre A Jour les TDB", _
             .Command = New DelegateCommand(Of Object)(AddressOf ResfreshAllDashboards)})


    End Sub
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Unload() Implements Common.IModule.Unload

    End Sub


    Private Shared filesaveassociation As New Dictionary(Of Object, String)

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub AddDashboardModelDefinitionExecute(ByVal parameter As Object)
        Dim ui = _AppInstance.GetService(Of IUIService)()
        Dim dbinfo = New VMDashboardLayoutDefinition() With {.Name = "Tableau de Bord"}
        ui.ShowMessage(dbinfo)

        Dim dbnode = New V2ViewModelTabGroup() With { _
          .Title = dbinfo.Name, _
          .TabGroup = dashboardmodels.TabGroup}



        dashboardmodels.Children.Add(dbnode)

        'dbnode.ContextualCommands.Add( _
        '    New ViewModelCommand("Ajouter un modele de tableau de bord", _
        '            New DelegateCommand(AddressOf AddDashboardModelExecute, _
        '                                AddressOf AddDashboardModelCanExecute)))

        Dim dbdef = New VMDashboardDefinition(dbinfo) With {.Title = dbinfo.Name}
        dbnode.TabSection = dbdef
        dashboardmodels.TabGroup.Add(dbdef)

        Dim addzone = Sub(p As Object)
                          Dim zoneinfo = New VMDashboardDefinitionZone()
                          zoneinfo.MaxColumns = dbinfo.ColumnCount
                          zoneinfo.MaxRows = dbinfo.RowCount
                          ui.ShowMessage(zoneinfo)
                          If zoneinfo.SelectedZoneType IsNot Nothing Then
                              If zoneinfo.SelectedZoneType.Type IsNot Nothing Then
                                  If zoneinfo.SelectedZoneType.IsFacade Then
                                      Dim f As Facades.IFacade = Activator.CreateInstance(zoneinfo.SelectedZoneType.Type)
                                      zoneinfo.GraphDefinition.DetailInstance = f.Brother
                                      zoneinfo.GraphDefinition.Detail = New VMEditableObject(f)
                                  Else
                                      zoneinfo.GraphDefinition.DetailInstance = Activator.CreateInstance(zoneinfo.SelectedZoneType.Type)
                                  End If
                              End If
                              dbdef.Zones.Add(zoneinfo)

                              Dim urtoken = New UndoRedoToken()
                              urtoken.Data = zoneinfo
                              urtoken.Display = "Ajouter une Zone"
                              urtoken.UndoMethod = Sub(obj As Object) dbdef.Zones.Remove(obj)
                              urtoken.RedoMethod = Sub(obj As Object) dbdef.Zones.Add(obj)

                              _AppInstance.GetService(Of IUndoRedoService)().Push(urtoken)
                          End If
                      End Sub

        dbnode.ContextualCommands.Add( _
            New ViewModelCommand("Ajouter une zone", _
               New DelegateCommand(Of Object)(addzone)))


        Dim savedb = Sub(p As Object)
                         Dim sdlg = New Microsoft.Win32.SaveFileDialog()
                         sdlg.DefaultExt = "tbb"
                         sdlg.Filter = "Fichiers Tableau-de-Bord(*.tbb)|*.tbb"

                         If sdlg.ShowDialog() Then
                             Dim x = dbdef.ToXElement()

                             x.Save(sdlg.FileName)

                             If filesaveassociation.ContainsKey(dbdef) Then
                                 filesaveassociation(dbdef) = sdlg.FileName
                             Else
                                 filesaveassociation.Add(dbdef, sdlg.FileName)
                             End If
                         End If
                     End Sub

        Dim savemodifdb = Sub(p As Object)
                              If filesaveassociation.ContainsKey(dbdef) Then
                                  Dim x = dbdef.ToXElement()

                                  x.Save(filesaveassociation(dbdef))
                              Else
                                  savedb(Nothing)
                              End If
                          End Sub

        Dim deletedb = Sub(p As Object)
                           dashboardmodels.Children.Remove(dbnode)
                           dashboardmodels.TabGroup.Remove(dbdef)
                       End Sub

        dbnode.ContextualCommands.Add( _
           New ViewModelCommand("Enrégistrer sous ...", _
              New DelegateCommand(Of Object)(savedb)))

        dbnode.ContextualCommands.Add( _
           New ViewModelCommand("Enrégistrer les modifications", _
              New DelegateCommand(Of Object)(savemodifdb)))

        dbnode.ContextualCommands.Add( _
          New ViewModelCommand("Supprimer", _
             New DelegateCommand(Of Object)(deletedb)))
    End Sub



    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Private Function AddDashboardModelDefinitionCanExecute(ByVal parameter As Object) As Boolean
        Return True
    End Function
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub LoadDashboardModelDefinitionExecute(ByVal parameter As Object)
        Dim cd = Function(s As String) Double.Parse(s, Globalization.CultureInfo.InvariantCulture)
        Dim cc = Function(s As String) Windows.Media.ColorConverter.ConvertFromString(s)



        Dim sdlg = New Microsoft.Win32.OpenFileDialog()
        sdlg.DefaultExt = "tbb"
        sdlg.Filter = "Fichiers Tableau-de-Bord(*.tbb)|*.tbb"

        If sdlg.ShowDialog() Then
            Dim x = XElement.Load(sdlg.FileName)
            Dim dbinfo = New VMDashboardLayoutDefinition() With {.Name = "Tableau de Bord"}
            Try
                dbinfo.Name = x.@Name
            Catch ex As Exception

            End Try
            dbinfo.RowCount = x.@RowCount
            dbinfo.ColumnCount = x.@ColumnCount

            Dim dbdef = New VMDashboardDefinition(dbinfo) With {.Title = If(String.IsNullOrEmpty(dbinfo.Name), "(Sans Nom)", dbinfo.Name)}

            dbdef.FromXElement(x)


            Dim dbnode = New V2ViewModelTabGroup() With { _
                .Title = If(String.IsNullOrEmpty(dbinfo.Name), "(Sans Nom)", dbinfo.Name), _
                .TabGroup = dashboardmodels.TabGroup}

            dashboardmodels.Children.Add(dbnode)

            dbnode.TabSection = dbdef
            dashboardmodels.TabGroup.Add(dbdef)

            Dim ui = _AppInstance.GetService(Of IUIService)()


            Dim addzone = Sub(p As Object)
                              Dim zoneinfo = New VMDashboardDefinitionZone()
                              zoneinfo.MaxColumns = dbinfo.ColumnCount
                              zoneinfo.MaxRows = dbinfo.RowCount
                              UI.ShowMessage(zoneinfo)
                              If zoneinfo.SelectedZoneType IsNot Nothing Then
                                  If zoneinfo.SelectedZoneType.Type IsNot Nothing Then
                                      If zoneinfo.SelectedZoneType.IsFacade Then
                                          Dim f As Facades.IFacade = Activator.CreateInstance(zoneinfo.SelectedZoneType.Type)
                                          zoneinfo.GraphDefinition.DetailInstance = f.Brother
                                          zoneinfo.GraphDefinition.Detail = New VMEditableObject(f)
                                      Else
                                          zoneinfo.GraphDefinition.DetailInstance = Activator.CreateInstance(zoneinfo.SelectedZoneType.Type)
                                      End If
                                  End If
                                  dbdef.Zones.Add(zoneinfo)

                                  Dim urtoken = New UndoRedoToken()
                                  urtoken.Data = zoneinfo
                                  urtoken.Display = "Ajouter une Zone"
                                  urtoken.UndoMethod = Sub(obj As Object) dbdef.Zones.Remove(obj)
                                  urtoken.RedoMethod = Sub(obj As Object) dbdef.Zones.Add(obj)

                                  _AppInstance.GetService(Of IUndoRedoService)().Push(urtoken)
                              End If
                          End Sub

            dbnode.ContextualCommands.Add( _
                New ViewModelCommand("Ajouter une zone", _
                   New DelegateCommand(Of Object)(addzone)))


            Dim savedb = Sub(p As Object)
                             Dim sdlg2 = New Microsoft.Win32.SaveFileDialog()
                             sdlg2.DefaultExt = "tbb"
                             sdlg2.Filter = "Fichiers Tableau-de-Bord(*.tbb)|*.tbb"

                             If sdlg2.ShowDialog() Then
                                 Dim x2 = dbdef.ToXElement()

                                 x2.Save(sdlg2.FileName)

                                 If filesaveassociation.ContainsKey(dbdef) Then
                                     filesaveassociation(dbdef) = sdlg2.FileName
                                 Else
                                     filesaveassociation.Add(dbdef, sdlg2.FileName)
                                 End If
                             End If
                         End Sub

            Dim savemodifdb = Sub(p As Object)
                                  If filesaveassociation.ContainsKey(dbdef) Then
                                      Dim x2 = dbdef.ToXElement()

                                      x2.Save(filesaveassociation(dbdef))
                                  Else
                                      savedb(Nothing)
                                  End If
                              End Sub

            Dim deletedb = Sub(p As Object)
                               dashboardmodels.Children.Remove(dbnode)
                               dashboardmodels.TabGroup.Remove(dbdef)
                           End Sub

            dbnode.ContextualCommands.Add( _
               New ViewModelCommand("Enrégistrer sous ...", _
                  New DelegateCommand(Of Object)(savedb)))

            dbnode.ContextualCommands.Add( _
               New ViewModelCommand("Enrégistrer les modifications", _
                  New DelegateCommand(Of Object)(savemodifdb)))

            dbnode.ContextualCommands.Add( _
              New ViewModelCommand("Supprimer", _
                 New DelegateCommand(Of Object)(deletedb)))
        End If
    End Sub
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Private Function LoadDashboardModelDefinitionCanExecute(ByVal parameter As Object) As Boolean
        Return True
    End Function

    Private Sub LoadDashboardModel(ByVal parameter As Object)
        MuteAllQuery = True
        Dim odlg = New Microsoft.Win32.OpenFileDialog()
        odlg.DefaultExt = "tbb"
        odlg.Filter = "Fichiers Tableau-de-Bord(*.tbb)|*.tbb"

        If odlg.ShowDialog() Then

        End If
    End Sub
    Private Sub LoadGroupDashboardModel(ByVal parameter As Object)
        MuteAllQuery = True
        Dim odlg = New Microsoft.Win32.OpenFileDialog()
        odlg.DefaultExt = "tbb"
        odlg.Filter = "Fichiers Tableau-de-Bord(*.tbb)|*.tbb"

        If odlg.ShowDialog() Then
            Dim x = XElement.Load(odlg.FileName)
            Dim dbinfo = New VMDashboardLayoutDefinition() With {.Name = "Tableau de Bord"}
            Try
                dbinfo.Name = x.@Name
            Catch ex As Exception

            End Try
            dbinfo.RowCount = x.@RowCount
            dbinfo.ColumnCount = x.@ColumnCount

            Dim dbdef = New VMDashboardDefinition(dbinfo) With {.Title = If(String.IsNullOrEmpty(dbinfo.Name), "(Sans Nom)", dbinfo.Name)}

            dbdef.FromXElement(x)

            Dim v = New VMDashboard(dbdef, dbdef.Title & " " & Now)
            dimensionglobal.TabGroup.Add(v)
            dimensionglobal.TabSection = v

            For Each c As V2ViewModelTabGroup In dimensionBanque.Children
                Dim cv = New VMDashboard(dbdef, c.Title & " " & dbdef.Title & " " & Now)
                'c.TabGroup = New ObservableCollection(Of IViewModelTabSection)
                c.TabGroup.Add(cv)
                c.TabSection = cv
            Next
        End If
    End Sub

    Private Sub LoadDashboardModelExecute(ByVal parameter As Object)
        MuteAllQuery = True
        Dim odlg = New Microsoft.Win32.OpenFileDialog()

        If odlg.ShowDialog() Then

            Dim func = Function(toi As Type)
                           Dim r = toi.GetCustomAttributes(GetType(SerializableAttribute), True)
                           If r Is Nothing Then Return False
                           If r.Length < 1 Then Return False
                           Return True
                       End Function

            Dim mps As Services.ZoneProviderService = AppInstance.GetService(Of Services.IZoneProviderService)()

            Dim oop = (From zt In mps.ZoneTypes _
                         Where func(zt.Type) _
                         Select zt.Type).ToArray()

            Dim ser As New XmlSerializer(GetType(VMDashboardDefinition()), oop)



            Try
                Dim f = IO.File.Open(odlg.FileName, IO.FileMode.Open)
                Dim o = ser.Deserialize(f)
                f.Close()
                f.Dispose()
                f = Nothing

                Dim defarray As VMDashboardDefinition() = o
                Dim ddboard = From oelt In defarray Select New VMDashboard(oelt, "")
                Dim ggrp = New ObservableCollection(Of IViewModelTabSection)(ddboard.ToArray())
                dimensionglobal.TabGroup = ggrp
                dimensionglobal.TabSection = ggrp(0)
            Catch ex As Exception

            End Try

            For Each elt In Banques
                Try
                    Dim f = IO.File.Open(odlg.FileName, IO.FileMode.Open)
                    Dim o = ser.Deserialize(f)
                    f.Close()
                    f.Dispose()
                    f = Nothing

                    Dim defarray As VMDashboardDefinition() = o
                    Dim dboard = From oelt In defarray Select New VMDashboard(oelt, elt.Key(1))
                    Dim grp = New ObservableCollection(Of IViewModelTabSection)(dboard.ToArray())

                    elt.Value.TabGroup = grp
                    elt.Value.TabSection = grp(0)
                Catch ex As Exception

                End Try

            Next
            'For Each elt In DateEncours

            '    Dim dboard = From oelt In defarray Select New VMDashboard(oelt, elt.Key(1))
            '    Dim grp = New ObservableCollection(Of IViewModelTabSection)(dboard.ToArray())

            '    elt.Value.TabSection = grp(0)
            '    elt.Value.TabGroup = grp
            'Next
            'For Each elt In DimensionTotals

            '    Dim dboard = From oelt In defarray Select New VMDashboard(oelt, elt.Key(0))
            '    Dim grp = New ObservableCollection(Of IViewModelTabSection)(dboard.ToArray())

            '    elt.Value.TabSection = grp(0)
            '    elt.Value.TabGroup = grp
            'Next

        End If
        MuteAllQuery = False
    End Sub
    Private Sub ConfigureDataSourceExecute(ByVal parameter As Object)
        Dim ui = _AppInstance.GetService(Of IUIService)()
        If currentDataConfig Is Nothing Then
            currentDataConfig = New VMDataSourceConfigure()
        End If


        ui.ShowMessage(currentDataConfig)
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Friend Shared ReadOnly Property AppInstance As Application
        Get
            Return _AppInstance
        End Get
    End Property
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Friend Shared ReadOnly Property BddInstance As BddManager
        Get
            Return _BddManager
        End Get
    End Property

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ResfreshAllDashboards(ByVal parameter As Object)
        '  Model.Instance.UpdateAll()

        'Dim w = Windows.Application.Current.MainWindow
        'Dim pdlg = New Windows.Controls.PrintDialog()
        'If pdlg.ShowDialog() Then

        '    pdlg.PrintVisual(w, "ouw wou hou")
        'End If
        MuteAllQuery = False
        For Each elt2 As VMDashboard In dimensionglobal.TabGroup
            elt2.Refresh()
        Next
        For Each elt In Banques
            For Each elt2 As VMDashboard In elt.Value.TabGroup
                elt2.Refresh()
            Next
        Next

        Return
        Dim func = Function(toi As Type)
                       Dim r = toi.GetCustomAttributes(GetType(SerializableAttribute), True)
                       If r Is Nothing Then Return False
                       If r.Length < 1 Then Return False
                       Return True
                   End Function

        Dim mps As Services.ZoneProviderService = AppInstance.GetService(Of Services.IZoneProviderService)()

        Dim oop = (From zt In mps.ZoneTypes _
                     Where func(zt.Type) _
                     Select zt.Type).ToArray()

        Dim ser As New XmlSerializer(GetType(VMDashboardDefinition()), oop)
        Dim dbmdls = From elt In dashboardmodels.Children.Cast(Of V2ViewModelTabGroup)()
                     Select CType(elt.TabSection, VMDashboardDefinition)


        Dim f = IO.File.Open("tdbmodels_all1.xml", IO.FileMode.Truncate)
        ser.Serialize(f, dbmdls.ToArray())
        f.Close()
        f.Dispose()
        f = Nothing

        Return



        Dim tbl = ModuleIndicateurs.BddInstance.ListeTraitements.TraitTbleEncours
        Dim nomtrait = "ohgod"
        Dim req = New RequeteBDD(nomtrait, _
                        New Cla_NomFichier(PTIC_Util.csteEmplacementCalculsInt & nomtrait & ".sas7bdat"), _
                        PTIC_Util.csteLibSASCalculsInt, _
                        ModuleIndicateurs.BddInstance.Connection.Connection)
        AddHandler req.EtatCalculDataTableAChange, AddressOf ReqEtatCalculDataTableAChange
        req.addTraitementConstitutif(tbl)
        req.addSELECT(tbl.nom, "Identifiant Réseau")

        req.Calculer_DataTable()

        Dim t As DataTable = req.DataTableResultat
        Dim s As String = "t"


        '' req.addGROUPBY(tbl.ListeChampsSortie("Sexe de l'assuré").chOutil.Nom)
        'req.addSELECT(tbl.ListeChampsSortie("Capital assuré").chOutil.Nom)

        'Dim tble = BddInstance.ListeTraitements.TraitTbleEncours

        'req.Calculer_DataTable()
        ''    Dim dtble = tble.execute_DataTableSortie(False)

        'req.Calculer_BDD()
        ' _AppInstance.GetService(Of IUIService)().ShowMessage(New VMSqlQuery())

        '  req.DataTableResultat
    End Sub



    Private Sub ReqEtatCalculDataTableAChange(ByVal sender As Object, ByVal e As EventArgs)
        Dim r = TryCast(sender, RequeteBDD)
        If r Is Nothing Then Return
        If r.EtatCalcul_DataTable = PTIC_Util.ValueEtatCalcul.A_JOUR Then
            Dim o = r.DataTableResultat
        End If
    End Sub

    Private Sub AddDataModelExecute(ByVal parameter As Object)

        Dim vmdm = New VMDataModel()
        vmdm.Title = InputBox("Nom du Modele")
        datamodels.TabGroup.Add(vmdm)

        Dim datanode = New V2ViewModelTabGroup() With { _
       .Title = vmdm.Title, _
       .TabSection = vmdm, _
       .TabGroup = datamodels.TabGroup}


        datamodels.Children.Add(datanode)

    End Sub

    Private Sub LoadDataModelExecute(ByVal parameter As Object)
    End Sub

End Class

''' <summary>
''' 
''' </summary>
''' <remarks></remarks>
Public Class BddManager
    Inherits UniversBDD

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Sub New(ByVal ConnectionSAS As ConnectionSAS)
        MyBase.New(ConnectionSAS)
        'Connections à créer
        m_CollTraitementsTxGarantis = New ListeTraitementsOMANE(Me)
        'initInformat()
    End Sub



    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub initLibrairieEncours(ByVal nomFichierConnection As Cla_NomFichier)
        Me.Connection.AssignLibName(nomFichierConnection.NomRepertoire, PTIC_Util.csteLibSASEncours)
    End Sub


    Private m_CollTraitementsTxGarantis As ListeTraitementsOMANE
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Public Overloads ReadOnly Property ListeTraitements() As ListeTraitementsOMANE
        Get
            Return m_CollTraitementsTxGarantis
        End Get
    End Property

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub initInformat()
        'Chargement des conversions de format possibles (disponibles au format XML)
        informatChampsBDD.MAJ_conversionsPossibles(PTIC_Util.csteEmplacementParametrage & "lstInformat.xml")
    End Sub
End Class

''' <summary>
''' 
''' </summary>
''' <remarks></remarks>
Public Class ListeTraitementsOMANE
    Inherits Dictionary(Of String, PTIC_GestionBDD.ITraitement)
    Implements IListeTraitementsOMANE

    Private manager As BddManager

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Friend Sub New(ByVal manager As BddManager)
        Me.manager = manager
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Public ReadOnly Property TraitTbleEncours As PTIC_GestionBDD.tableBDD Implements IListeTraitementsOMANE.TraitTbleEncours
        Get
            If Not ContainsKey(PTIC_Util.nomTraitTbleEncours) Then
                creeTraitTbleEncours()
            End If
            Dim result As tableBDD = Item(PTIC_Util.nomTraitTbleEncours)
            'Dim e As New PropertyGetEventArgs(Of tableBDD)(result, result)
            'RaiseEvent TraitTbleEncoursGet(Me, e)
            Return result
        End Get
    End Property

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Protected Function creeTraitTbleEncours() As Boolean
        Dim result As Boolean = True
        Try
            'Initialiseur (création du mapping en sortie de la table d'encours)
            Dim initialiseurTableBDD As New initialiseurTableBDDEncours(PTIC_Util.csteEmplacementParametrage & "lstMappingEncours.xml")
            Add(PTIC_Util.nomTraitTbleEncours, New TableBDD_SAS(PTIC_Util.nomTraitTbleEncours, _
                                                                    PTIC_Util.csteLibSASEncours, _
                                                                    initialiseurTableBDD, _
                                                                    manager))
        Catch ex As Exception
            result = False
        End Try
        Return result
    End Function
End Class

''' <summary>
''' 
''' </summary>
''' <remarks></remarks>
Public Interface IListeTraitementsOMANE
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    ReadOnly Property TraitTbleEncours As tableBDD
End Interface

Public NotInheritable Class Indicateus

    Private Computed As Boolean = True

    Shared _Instance As Indicateus

    Public Shared ReadOnly Property Instance As Indicateus
        Get
            If _Instance Is Nothing Then
                _Instance = New Indicateus()
            End If
            Return _Instance
        End Get
    End Property

    Private _CorrespBanque As Correspondance
    Public ReadOnly Property CorrespBanque As Correspondance
        Get
            If _CorrespBanque Is Nothing Then
                Dim tbl = ModuleIndicateurs.BddInstance.ListeTraitements.TraitTbleEncours
                _CorrespBanque = tbl.ListeChampsSortie("Identifiant Partenaire")
            End If
            Return _CorrespBanque
        End Get
    End Property

    Public Function CapBy(ByVal byvar As String, Optional ByVal banque As String = "") As IEnumerable
        Throw New NotImplementedException()

    End Function

    Public Function CapBySexe(Optional ByVal banque As String = "") As IEnumerable
        Throw New NotImplementedException()

    End Function


    Public Function GetCount() As Double
        Throw New NotImplementedException()

    End Function

#Region "Repartitions"

    Public Function GetRepartition(ByVal byvar As String, Optional ByVal banque As String = "") As IEnumerable
        Dim name = "Repartition_[" & byvar & "]" & _
            If(String.IsNullOrEmpty(banque), "", "_[" & banque & "]")
        If IsInStock(name) Then Return GetFromStock(name)

        Dim tbl = ModuleIndicateurs.BddInstance.ListeTraitements.TraitTbleEncours
        Dim nomtrait = "traitement_" & Guid.NewGuid().ToString("N")
        Dim req = New RequeteBDD(nomtrait, _
                        New Cla_NomFichier(PTIC_Util.csteEmplacementCalculsInt & nomtrait & ".sas7bdat"), _
                        PTIC_Util.csteLibSASCalculsInt, _
                        ModuleIndicateurs.BddInstance.Connection.Connection)

        req.isDISTINCT = False
        req.addTraitementConstitutif(tbl)
        req.addSELECT(tbl.nom, byvar)
        req.addSELECTcalculee( _
            New String() {tbl.nom}, _
            New String() {byvar}, _
            "count({1})", _
            "Nombre", _
            "Nombre de Lignes")

        If Not String.IsNullOrEmpty(banque) Then
            req.addWHERE("filtre", CorrespBanque, operateurFiltreBDD.Egal, """" & banque & """")
        End If

        req.addGROUPBY(tbl.nom, byvar)

        req.Calculer_DataTable()

        'Dim t As DataTable = req.DataTableResultat
        'Dim s As String = "t"
        'If req.DataTableResultat Is Nothing Then Return

        Dim data = (From elt As DataRowView In req.DataTableResultat.DefaultView
                     Select X = elt("Nombre"), Lbl = elt(0)).ToArray()

        SaveToStock(name, data)

        Return data
    End Function

    Public Function GetRepartitionBySexe(Optional ByVal banque As String = "")
        Return GetRepartition("Sexe de l'assuré", banque)
    End Function
    Public Function GetRepartitionByOption(Optional ByVal banque As String = "")
        Return GetRepartition("Identifiant option", banque)
    End Function
    Public Function GetRepartitionByPret(Optional ByVal banque As String = "")
        Return GetRepartition("Identifiant type de prêt", banque)
    End Function

#End Region

#Region "Durées"

#End Region

#Region "Capitaux"

#End Region

#Region "Taux Moyen"

#End Region

    Private stock As Dictionary(Of String, IEnumerable)

    Public Function GetFromStock(ByVal name As String) As IEnumerable
        Return stock(name)
    End Function
    Public Function IsInStock(ByVal name As String) As Boolean
        If stock Is Nothing Then
            stock = New Dictionary(Of String, IEnumerable)()
        End If
        If stock.ContainsKey(name) Then
            Return True
        Else
            If IO.File.Exists(name & ".xml") Then
                Try
                    Dim f = XElement.Load(name & ".xml")
                    Dim q = From e In f.<Value>
                            Select X = Convert.ToDouble(e.<X>.First().Value, Globalization.CultureInfo.InvariantCulture),
                                  Lbl = e.<Lbl>.First().Value
                    stock.Add(name, q.ToArray())
                    Return True
                Catch ex As Exception
                    Return False
                End Try
            Else
                Return False
            End If
        End If
    End Function
    Public Sub SaveToStock(ByVal name As String, ByVal data As IEnumerable)

        If stock.ContainsKey(name) Then
            stock(name) = data
        Else
            Dim q = From e In data
            Select <Value>
                       <X><%= e.X %></X>
                       <Lbl><%= e.Lbl %></Lbl>
                   </Value>

            Dim xxx = <Data><%= q.ToArray() %></Data>
            xxx.Save(name & ".xml")
            stock.Add(name, data)
        End If
    End Sub
    Public Function GetIndicateur(ByVal name As String, Optional ByVal banque As String = "") As IEnumerable
        If name = RepartitionBySexeName Then
            Return GetRepartitionBySexe(banque)
        End If
        If name = RepartitionByOptionName Then
            Return GetRepartitionByOption(banque)
        End If
        If name = RepartitionByPretName Then
            Return GetRepartitionByPret(banque)
        End If
        Return Nothing
    End Function

    Public Const RepartitionBySexeName = "RepartitionBySexe"
    Public Const RepartitionByOptionName = "RepartitionByOption"
    Public Const RepartitionByPretName = "RepartitionByPret"

End Class